package com.jcj.pojomessagepack;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * 测试基于MessagePack的实体对象传输
 */
@ChannelHandler.Sharable
public class HandlerClientPM extends SimpleChannelInboundHandler<Infomation> {


    /**
     * 处理接收到的消息
     *
     * @param channelHandlerContext 通道的上下文
     * @param info                  接收字节序
     */
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Infomation info) throws Exception {

        System.out.println("收到的实体对象: " + info);
        System.out.println("具体数据内容: " + info.getContent());

    }

    /**
     * 处理I/O事件的异常
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();//关闭当前Channel的连接
    }

    /**
     * 建立连接后该channelActive()方法只会被调用一次,这里的逻辑:建立连接后,字节序列被发送到服务器,编码格式是utf-8
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        Infomation info = new Infomation();
        info.setHeader((short) 0x5AA);
        info.setMsgtype((byte) 0x01);
        info.setContent("你好,天王盖地虎!");
        System.out.println("发送了一条消息:" + info.getContent());

        ctx.writeAndFlush(info);
    }
}






























































